import { formatDate } from "@/utils/formatTime";

export function toOptions(data) {
  if (!data) return [];
  const result = {};
  for (var i = 0; i < data.length; i++) {
    for (var key in data[i]) {
      var item = result[key] ? result[key] : [];
      item[i] = data[i][key];
      result[key] = item;
    }
  }
  return result;
}

export function toTable(data) {
  const result = [];
  for (let key in data) {
    if (!data[key]) return [];
    for (var i = 0; i < data[key].length; i++) {
      var item = result[i] ? result[i] : {};
      item[key] = data[key][i];
      result[i] = item;
    }
  }
  return result;
}

export function toTableCustom(data, titles) {
  if (!data) return [];
  var result = {};
  for (var i = 0; i < titles.length; i++) {
    var key = titles[i];
    result[key] = data[key];
  }
  return toTable(result);
}

export function tLabel(t) {
  if (!t || !new Date(t[0]).getDate()) return t;
  // var date = t.map((x) => new Date(x.replace(/\"/g, "")));
  // var result = [];
  // for (var i = 0; i < date.length; i++) {
  //   // if (i == 0 || date[i].getDate() != date[i - 1].getDate()) {
  //   //   result[i] = formatDate(date[i], "mm-dd HH时");
  //   // } else result[i] = formatDate(date[i], "HH时");
  //   result[i] = formatDate(date[i], "mm/dd\nHH时");
  // }
  var result = t.map((x) => x.replace(":00:00", ":30:00"));
  return result;
}

export function toSeries(x, y) {
  // var result = [];
  // for (var i = 0; i < y.length; i++) {
  //   result[i] = [x[i], y[i]];
  // }
  if (!x || !y) return [];
  var result = x.map((x, index) => [x, y && y[index] ? y[index] : 0]);
  return result;
}

export function hexToRgba(hex, opacity) {
  let rgbaColor = "";
  let reg = /^#[\da-f]{6}$/i;
  if (reg.test(hex)) {
    rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
      "0x" + hex.slice(3, 5)
    )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
  }
  return rgbaColor;
}

//线性插值
//times数据的时间序列
//props，待插值的数据
//t: 规定的时间序列(不规定则表示从起始日0时到结束日23时)
export function interpolate(times, props, t = null) {
  if (!t) {
    var start = new Date(formatDate(new Date(times[0]), "YYYY-mm-dd 00:00:00"));
    var end = new Date(
      formatDate(new Date(times[times.length - 1]), "YYYY-mm-dd 23:00:00")
    );
    var dh = (end - start) / 3600000 + 1;
    t = [...Array(dh)].map(
      (x, index) =>
        (x = formatDate(
          index === 0 ? start : new Date(start.setHours(start.getHours() + 1)),
          "YYYY-mm-dd HH:00:00"
        ))
    );
  }
  var result = { t: t };
  if (times.length == 1) {
    for (key in props)
      result[key] = [...Array(t.length)].map((x) => props[key][0]);
    return result;
  }
  for (var i = 0; i < t.length; i++) {
    var idx = times.indexOf(t[i]);
    if (idx < 0) {
      var t1 = new Date(t[i]);
      var t2 = times.map((x) => new Date(x));
      if (t2[0] > t1 && t2[1] > t1) idx = 0;
      else if (t2[t2.length - 2] < t1 && t2[t2.length - 1] < t1)
        idx = t2.length - 2;
      else idx = t2.findIndex((x, idx) => x < t1 && t2[idx + 1] > t1);
      var dt = Math.floor(
        (new Date(times[idx + 1]) - new Date(times[idx])) / 3600000
      );
      for (var key in props) {
        var y0 = props[key][idx];
        var dy = props[key][idx + 1] - props[key][idx];
        var d = dy / dt;
        if (!result[key]) result[key] = [];
        var y = y0 + d * Math.floor((t1 - t2[idx]) / 3600000);
        result[key][i] = Math.round(y * 10) / 10;
      }
    } else {
      for (var key in props) {
        if (!result[key]) result[key] = [];
        result[key][i] = props[key][idx];
      }
    }
  }
  return result;
}

export function toUnitData(t, data) {
  var result_total = { t: [], js1: [], js2: [], js3: [], js4: [] };
  var result = { t: [], power_real: [], unit_real: [] };
  var start_date = new Date(data[0].hour_time);
  data.forEach((x) => {
    if (!result_total.t.includes(x.hour_time)) result_total.t.push(x.hour_time);
    var date = new Date(x.hour_time);
    var idx = (date - start_date) / 3600000;
    result_total[x.pid][idx] = x.power_value;
  });

  var idx = result_total.t.findIndex((x) => x == t[0]);
  for (var i = 0; i < t.length; i++) {
    if (idx + i + 1 == result_total.t.length) break;
    result.t[i] = t[i];
    result.power_real[i] = 0;
    result.unit_real[i] = 0;
    for (var j = 1; j <= 4; j++) {
      result.power_real[i] += result_total["js" + j][idx + i];
      if (result_total["js" + j][idx + i] != 0) result.unit_real[i]++;
    }
  }
  result.power_real.forEach((x, idx) => (result.power_real[idx] = x));
  return result;
}

export function toGateData(data) {
  var result = [];
  data.forEach((x) => {
    var idx = parseInt(x.NAME.match(/\d+#/)) - 1;
    if (!result[idx]) result[idx] = { t: [], e: [] };
    if (!result[idx].t.includes(x.HOUR_TIME)) {
      result[idx].t.push(x.HOUR_TIME);
      result[idx].e.push(parseFloat(x.VALUE) / 1000);
    }
  });
  return result;
}

export function toGateOpen(data) {
  var e = new Array(56).fill(0);
  data.forEach((x) => {
    x.order.forEach((id) => {
      if (id > 0) e[id - 1] = data[0].e;
    });
  });
  return e;
}

export function getAxisMax(max) {
  let digit = Math.ceil(max).toFixed(0).length;
  digit = Math.pow(10, digit - 1);
  if (max < 50) digit = 5;
  else if (max < 10) digit = 1;
  return Math.ceil((max * 1.1) / digit) * digit;
}

export function toExportData(data, keyMapper) {
  if (!keyMapper) keyMapper = { q_t: "流量(m³/s)", t: "时间", z_t: "水位(米)" };
  var result = data.map((x) => {
    var item = {};
    for (var key in x) {
      if (key in keyMapper) item[keyMapper[key]] = x[key];
      // else item[key] = x[key];
    }
    return item;
  });
  return result;
}

export function toSystemData(data, keyMapper) {
  if (!keyMapper)
    keyMapper = { "流量(m³/s)": "q_t", 时间: "t", "水位(米)": "z_t" };
  var result = data.map((x) => {
    var item = {};
    for (var key in x) {
      if (key in keyMapper) item[keyMapper[key]] = x[key];
      else item[key] = x[key];
    }
    return item;
  });
  return result;
}

//range: [min,max]正常取值范围, x在此范围内容评分为满分
//tol: [lower,upper]容忍值, x超出(低于)最大(小)值对应容忍值, 则评分为0分
export function rate_sqrt(x, range, tol) {
  if (range[1] < range[0]) {
    range = [range[1], range[0]];
  }
  var r = 0;
  if (x >= range[1]) {
    if (tol[1] > 0) r = Math.min(1, (x - range[1]) / tol[1]);
    else r = 1;
  } else if (x <= range[0]) {
    if (tol[0] > 0) r = Math.min(1, (range[0] - x) / tol[0]);
    else r = 1;
  }
  return 1 - Math.sqrt(r);
}

export function tSeries(start, end) {
  var result = [];
  for (var t = start.getTime(); t <= end.getTime(); t += 3600000) {
    result.push(formatDate(new Date(t), "YYYY-mm-dd HH:00:00"));
  }
  return result;
}

export function toPixel(w) {
  return Math.round((w * window.screen.width) / 1920);
}
